import React, { useState } from 'react';
import { Layout, Menu, Breadcrumb, Button, Dropdown } from 'antd';
import { useNavigate, Routes, Route, useLocation } from 'react-router-dom';
import {
  BookOutlined,
  CommentOutlined,
  QuestionCircleOutlined,
  DashboardOutlined,
  UserOutlined,
  VideoCameraOutlined,
  ReadOutlined,
  LogoutOutlined,
  MessageOutlined,
  HomeOutlined
} from '@ant-design/icons';
import { useSelector, useDispatch } from 'react-redux';
import { logout } from '../store/userSlice';

// 导入所有页面组件
import HomePage from '../pages/home/HomePage';
import CourseList from '../pages/courses/CourseList';
import CourseDetail from '../pages/courses/CourseDetail';
import LearningPage from '../pages/learning/LearningPage';
import DiscussionList from '../pages/discussion/DiscussionList';
import QAList from '../pages/qa/QAList';
import Dashboard from '../pages/admin/Dashboard';
import Profile from '../pages/user/Profile';
import BookManagement from '../pages/admin/BookManagement';
import AssignmentManagement from '../pages/admin/AssignmentManagement';
import DiscussionManagement from '../pages/admin/DiscussionManagement';
import UserManagement from '../pages/admin/UserManagement';
import CourseManagement from '../pages/admin/CourseManagement';

const { Header, Content, Sider } = Layout;

const MainLayout = () => {
  const [collapsed, setCollapsed] = useState(false);
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const user = useSelector(state => state.user.currentUser);
  const isAdmin = user?.role === 'admin';
  const location = useLocation();

  const handleLogout = () => {
    dispatch(logout());
    navigate('/login');
  };

  // 定义导航菜单项
  const menuItems = [
    {
      key: 'home',
      icon: <HomeOutlined />,
      label: '首页',
      onClick: () => navigate('/')
    },
    {
      key: 'courses',
      icon: <BookOutlined />,
      label: '课程中心',
      children: [
        {
          key: 'courseList',
          icon: <ReadOutlined />,
          label: '课程列表',
          onClick: () => navigate('/courses')
        },
        {
          key: 'learning',
          label: '我的学习',
          icon: <VideoCameraOutlined />,
          onClick: () => navigate('/learning')
        }
      ]
    },
    {
      key: 'community',
      icon: <CommentOutlined />,
      label: '社区交流',
      children: [
        {
          key: 'discussion',
          label: '讨论区',
          icon: <CommentOutlined />,
          onClick: () => navigate('/discussion')
        },
        {
          key: 'qa',
          label: '问答社区',
          icon: <QuestionCircleOutlined />,
          onClick: () => navigate('/qa')
        }
      ]
    },
    {
      key: 'user',
      icon: <UserOutlined />,
      label: '个人中心',
      onClick: () => navigate('/profile')
    }
  ];

  // 如果是管理员，添加管理菜单
  if (isAdmin) {
    menuItems.push({
      key: 'admin',
      icon: <DashboardOutlined />,
      label: '后台管理',
      children: [
        {
          key: 'dashboard',
          label: '仪表盘',
          icon: <DashboardOutlined />,
          onClick: () => navigate('/admin/dashboard')
        },
        {
          key: 'users',
          label: '用户管理',
          icon: <UserOutlined />,
          onClick: () => navigate('/admin/users')
        },
        {
          key: 'courses-manage',
          label: '课程管理',
          icon: <BookOutlined />,
          onClick: () => navigate('/admin/courses')
        },
        {
          key: 'assignments',
          label: '作业管理',
          icon: <ReadOutlined />,
          onClick: () => navigate('/admin/assignments')
        },
        {
          key: 'books',
          label: '图书管理',
          icon: <BookOutlined />,
          onClick: () => navigate('/admin/books')
        },
        {
          key: 'discussions',
          label: '讨论管理',
          icon: <MessageOutlined />,
          onClick: () => navigate('/admin/discussions')
        }
      ]
    });
  }

  // 生成面包屑项
  const getBreadcrumbItems = () => {
    const pathSnippets = location.pathname.split('/').filter(i => i);
    const items = [];

    items.push({
      title: '首页',
      onClick: () => navigate('/')
    });

    if (pathSnippets.length > 0) {
      switch (pathSnippets[0]) {
        case 'courses':
          items.push({
            title: '课程中心',
            onClick: () => navigate('/courses')
          });
          if (pathSnippets.length > 1) {
            items.push({
              title: '课程详情'
            });
          }
          break;
        case 'learning':
          items.push({
            title: '我的学习'
          });
          break;
        case 'discussion':
          items.push({
            title: '讨论区'
          });
          break;
        case 'qa':
          items.push({
            title: '问答社区'
          });
          break;
        case 'profile':
          items.push({
            title: '个人中心'
          });
          break;
        case 'admin':
          items.push({
            title: '后台管理'
          });
          break;
        default:
          break;
      }
    }

    return items;
  };

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Header style={{
        padding: '0 24px',
        background: '#fff',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
      }}>
        <div style={{
          fontSize: '20px',
          fontWeight: 'bold',
          color: '#1890ff'
        }}>
          在线学习平台
        </div>
        <div style={{
          display: 'flex',
          alignItems: 'center',
          gap: '16px'
        }}>
          <div style={{
            color: '#666',
            display: 'flex',
            alignItems: 'center',
            gap: '8px'
          }}>
            <UserOutlined />
            {user?.username || '用户'}
          </div>
          <Button 
            type="text" 
            icon={<LogoutOutlined />} 
            onClick={handleLogout}
            style={{ color: '#666' }}
          >
            退出登录
          </Button>
        </div>
      </Header>
      <Layout>
        <Sider
          collapsible
          collapsed={collapsed}
          onCollapse={setCollapsed}
          theme="light"
          width={200}
        >
          <Menu
            mode="inline"
            defaultSelectedKeys={['home']}
            defaultOpenKeys={['courses', 'community', 'admin']}
            style={{ height: '100%', borderRight: 0 }}
            items={menuItems}
          />
        </Sider>
        <Layout style={{ padding: '0 24px 24px' }}>
          <Breadcrumb style={{ margin: '16px 0' }}>
            {getBreadcrumbItems().map((item, index) => (
              <Breadcrumb.Item key={index}>
                {item.onClick ? (
                  <a onClick={item.onClick}>{item.title}</a>
                ) : (
                  item.title
                )}
              </Breadcrumb.Item>
            ))}
          </Breadcrumb>
          <Content style={{
            background: '#fff',
            padding: 24,
            margin: 0,
            minHeight: 280,
            borderRadius: 4
          }}>
            <Routes>
              <Route path="/" element={<HomePage />} />
              <Route path="/courses" element={<CourseList />} />
              <Route path="/courses/:id" element={<CourseDetail />} />
              <Route path="/learning" element={<LearningPage />} />
              <Route path="/discussion" element={<DiscussionList />} />
              <Route path="/qa" element={<QAList />} />
              <Route path="/profile" element={<Profile />} />
              {isAdmin && (
                <>
                  <Route path="/admin/dashboard" element={<Dashboard />} />
                  <Route path="/admin/users" element={<UserManagement />} />
                  <Route path="/admin/courses" element={<CourseManagement />} />
                  <Route path="/admin/assignments" element={<AssignmentManagement />} />
                  <Route path="/admin/books" element={<BookManagement />} />
                  <Route path="/admin/discussions" element={<DiscussionManagement />} />
                </>
              )}
            </Routes>
          </Content>
        </Layout>
      </Layout>
    </Layout>
  );
};

export default MainLayout;
